/**
 * Form 封装
 * 
 * 版本：v1.0
 * 
 * Stanley
 * 
 **/
layui.define(['jquery', 'form'],
    function (exports) {
        var $ = layui.jquery;
        var form = layui.form;
        var kaForm = new function () {
            this.veReSuccess = "success";
            this.veReError = "error";
            this.verifyReturnJson = function (boolean, msg, field) { // 验证统一返回JSON（提取公共方法）
                var verifyReturnJson = this.verifyReturn(boolean);
                verifyReturnJson.msg = msg;
                verifyReturnJson[this.veReError] = function () {
                    layui.kaMsg.error(msg, JSON.stringify(field));
                }
                return verifyReturnJson
            }
            this.verifyReturn = function (boolean) { // 验证码返回JSON
                return {
                    "boolean": boolean,
                    "success": function () { },
                    "error": function () { }
                }
            }
            this.verify = function (params) { // 验证码返回
                var verifyBoolean = {};
                var that = this;
                $.ajax({
                    url: "../kaForm/verify/" + params.type + ".js",
                    type: "GET",
                    dataType: "script",
                    async: false, //同步
                    success: function () {
                        var field = params.data.field;
                        for (var key in field) {
                            var verifyData = eval(params.type + "VerifyData")[key];
                            if (verifyData != undefined) {
                                var bl = verifyData(field, that);
                                if (bl != undefined) {
                                    verifyBoolean[key] = bl;
                                } else {
                                    var verifyReturnJson = that.verifyReturn(false);
                                    verifyReturnJson[that.veReError] = function () {
                                        top.layui.layer.msg("未配置对应", { icon: 2, skin: 'ka-error-layer', time: 3000 });
                                    }
                                    verifyBoolean[key] = verifyReturnJson;
                                }
                            } else {
                                verifyBoolean[key] = that.verifyReturn(true);
                            }
                        }
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        var field = params.data.field;
                        for (var key in field) {
                            verifyBoolean[key] = that.verifyReturn(true);
                        }
                        return verifyBoolean;
                    },
                    timeout: 5000 // 5秒超时
                });
                var fieldver = params.data.field;
                var fieldverNumber = 0;
                for (var i in fieldver) {
                    fieldverNumber++;
                }
                var verifyBooleanver = verifyBoolean;
                var verifyBooleanNumber = 0;
                for (var i in verifyBooleanver) {
                    verifyBooleanNumber++;
                }
                if (fieldverNumber == verifyBooleanNumber) {
                    return verifyBoolean;
                } else {
                    for (var key in fieldver) {
                        if (verifyBoolean[key] == undefined) {
                            var verifyReturnJson = that.verifyReturn(false);
                            verifyReturnJson[that.veReError] = function () {
                                top.layui.layer.msg("请检查验证脚本，脚本错误", { icon: 2, skin: 'ka-error-layer', time: 3000 });
                            }
                            verifyBoolean[key] = verifyReturnJson;
                        }
                    }
                    return verifyBoolean;
                }
            }
            this.submitEnd = function (params) { // 提交事件
                var that = this;
                $.ajax({
                    url: "../kaForm/submit/" + params.type + ".js",
                    type: "GET",
                    dataType: "script",
                    async: false, //同步
                    success: function () {
                        var field = params.data.field;
                        field.clientType = layui.kaPublic.isAppPhoneOrExe().type;//客户端类型
                        field.clientMsg = layui.kaPublic.isAppPhoneOrExe().appMsg;//客户端详细信息
                        var submitData = eval(params.type + "SubmitData");
                        if (submitData != undefined) {
                            submitData.init(field);
                        }
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        var field = params.data.field;
                        for (var key in field) {
                            verifyBoolean[key] = that.verifyReturn(true);
                        }
                        return verifyBoolean;
                    },
                    timeout: 5000 // 5秒超时
                });
            }
            this.pageEvents = function (params) { // 页面事件
                var that = this;
                if (params.type == 1) {
                    $.ajax({
                        url: "../kaForm/events/" + params.path + ".js",
                        type: "GET",
                        dataType: "script",
                        async: false, //同步
                        success: function () {
                            var field = {};
                            field.clientType = layui.kaPublic.isAppPhoneOrExe().type;//客户端类型
                            field.clientMsg = layui.kaPublic.isAppPhoneOrExe().appMsg;//客户端详细信息
                            var pageEventsData = eval(params.path + "PageEventsData");
                            if (pageEventsData != undefined) {
                                pageEventsData.init(field);
                            }
                        },
                        error: function (jqXHR, textStatus, errorThrown) {
                            var field = params.data.field;
                            for (var key in field) {
                                verifyBoolean[key] = that.verifyReturn(true);
                            }
                            return verifyBoolean;
                        },
                        timeout: 5000 // 5秒超时
                    });
                } else if (params.type == 2) {

                }
            }
            this.submit = function (id, verifyType, submitEndType, pageEventsType) { // 提交事件
                if (verifyType == undefined) { verifyType = id; }
                if (submitEndType == undefined) { submitEndType = id; }
                var that = this;
                if (pageEventsType != undefined) {
                    that.pageEvents(pageEventsType);
                }
                form.on('submit(' + id + ')', function (data) {
                    // 验证
                    layui.$(".kaXmSelectValue").each(function () {
                        var id = $(this).attr("id");
                        var name = $(this).attr("name");
                        var divpropvalue = $(this).attr("divpropvalue");
                        var divPropType = $(this).attr("divPropType");
                        var xmSelectMapData = window.xmSelectMap.get(id);
                        var selectArr = xmSelectMapData.getValue();
                        var djArray = [];
                        for (var i in selectArr) {
                            djArray.push(selectArr[i][divpropvalue]);
                        }
                        if(divPropType == "radio"){
                            if(djArray.length > 0){
                                data.field[name] = djArray.join(",");
                            }
                        } else {
                            data.field[name] = djArray;
                        }
                    });
                    var verifyBoolean = that.verify({ "type": verifyType, "data": data })
                    for (var i in verifyBoolean) {
                        if (verifyBoolean[i].boolean) {
                            verifyBoolean[i].success();
                        } else {
                            verifyBoolean[i].error();
                            return false
                        }
                    }
                    that.submitEnd({ "type": submitEndType, "data": data })
                    return false;
                });
            }
            this.rule = {  //判断 规则
                isNull: function (data) { // 判断为空
                    if (data != undefined && data != null && data != "") {
                        return false;
                    } else {
                        return true;
                    }
                },
                isMobile: function (data) { // 验证手机号码
                    var reg = /^1[3|4|5|7|8|9][0-9]\d{4,8}$/;//定义手机号正则表达式
                    if (reg.test(data)) {
                        return true;
                    } else {
                        return false;
                    }
                },
                isValidEmail: function (data) { // 验证邮箱
                    const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
                    return emailRegex.test(data);
                },
                isUserNameUniqueness: function (data) { // 用户唯一性
                    layui.kaAjax.ajax(layui.kaBgUrl.url("verifyUserNameUniqueness"), function (rs) { // rs 返回的驗證碼 JSON
                        if (rs.code == 200) {
                            return true;
                        } else {
                            return false;
                        }
                    }, { "userName": data });
                },
                isPhonenumberUniqueness: function (data) { // 用户唯一性
                    layui.kaAjax.ajax(layui.kaBgUrl.url("verifyPhonenumberUniqueness"), function (rs) { // rs 返回的驗證碼 JSON
                        if (rs.code == 200) {
                            return true;
                        } else {
                            return false;
                        }
                    }, { "phonenumber": data });
                }
            }
        };
        exports('kaForm', kaForm);
    }
)